﻿using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Web.Mvc;
using Fuse8.ContentManagementFramework.Administration.Controls;
using Fuse8.ContentManagementFramework.SystemFacade.Common;

namespace Fuse8.ContentManagementFramework.Administration.Controllers
{
    public class CmsAutocompleteController : CmsAdminController
    {
        public ActionResult Controllers()
        {
            return Json(AutocompleteListsManager.Controllers);
        }

        public ActionResult Actions(string controllerName)
        {
            return Json(AutocompleteListsManager.GetActions(controllerName));
        }
    }

    internal class AutocompleteListsManager
    {
        [ImportMany(typeof(Controller))]
        protected IEnumerable<Controller> AllControllers { get; set; }

        private static AutocompleteListsManager _facade;

        private static ConcurrentDictionary<string, List<string>> _controllers;

        public static IEnumerable<string> Controllers
        {
            get
            {
                InitControllers();

                return _controllers.Keys;
            }
        }

        public static IEnumerable<string> GetActions(string name)
        {
            InitControllers();

            return _controllers.ContainsKey(name) ? _controllers[name] : new List<string>();
        }

        private static void InitControllers()
        {
            if (_controllers == null)
            {
                InitFacade();

                var tempControllers = new ConcurrentDictionary<string, List<string>>();
                if (_facade.AllControllers != null)
                {
                    foreach (var controller in _facade.AllControllers)
                    {
                        var type = controller.GetType();
                        var name = type.Name.Replace("Controller", "");
                        var list = new List<string>();
                        foreach (var method in type.GetMethods())
                        {
                            if (method.GetCustomAttributes(typeof(ActionForPageControlAttribute), true).Length > 0)
                            {
                                list.Add(method.Name);
                            }
                        }
                        tempControllers.AddOrUpdate(name, s => list, (s, l) => list);
                    }
                    _controllers = tempControllers;    
                }
                
            }
        }

        private static void InitFacade()
        {
            if (_facade == null)
            {
                _facade = new AutocompleteListsManager();
                CmsExtensionManager.LoadExtensions(_facade);
            }
        }
    }

    

    

    
}